package service

import (
	"fmt"
	"log"
	"server/common"
	"server/model"
	"server/utils"
	"server/vo"

	"github.com/jinzhu/gorm"
)

type FormService struct {
	DB *gorm.DB
}

func NewFormService(db *gorm.DB) FormService {
	return FormService{DB: db}
}

// CreateFormSubmission is kept for backward compatibility
func (s *FormService) CreateFormSubmission(request vo.FormSubmissionRequest) error {
	// For backward compatibility, we don't process IP here
	formSubmission := model.FormSubmission{
		Name:            request.Name,
		Phone:           request.Phone,
		Email:           request.Email,
		Address:         request.Address,
		WhatsApp:        request.WhatsApp,
		DetailedRequest: request.DetailedRequest,
		Company:         request.Company,
	}

	if err := s.DB.Create(&formSubmission).Error; err != nil {
		return err
	}

	return nil
}

// CreateFormSubmissionWithIP creates a form submission with client IP address
func (s *FormService) CreateFormSubmissionWithIP(request vo.FormSubmissionRequest, clientIP string) error {
	// Resolve IP location using Baidu Maps API
	var ipLocation string
	var err error

	if clientIP != "" {
		ipLocation, err = utils.GetLocationFromIP(clientIP)
		if err != nil {
			// Log error but continue with submission
			// We don't want to fail the form submission just because IP resolution failed
			ipLocation = ""
			log.Printf("Failed to resolve IP location: %v", err)
		}
	}

	formSubmission := model.FormSubmission{
		Name:            request.Name,
		Phone:           request.Phone,
		Email:           request.Email,
		Address:         request.Address,
		WhatsApp:        request.WhatsApp,
		DetailedRequest: request.DetailedRequest,
		Company:         request.Company,
		IPAddress:       clientIP,
		IPLocation:      ipLocation,
	}

	if err := s.DB.Create(&formSubmission).Error; err != nil {
		log.Printf("Failed to save form submission to database: %v", err)
		return err
	}

	log.Printf("Form submitted successfully. Sending email notification...")

	// Send email notification
	if err := s.sendFormSubmissionEmail(request, clientIP, ipLocation); err != nil {
		// Log the error but don't fail the submission
		// We don't want to fail the form submission just because email sending failed
		log.Printf("Failed to send form submission email: %v", err)
	} else {
		log.Printf("Form submission email sent successfully")
	}

	return nil
}

// sendFormSubmissionEmail sends an email notification about the form submission
func (s *FormService) sendFormSubmissionEmail(request vo.FormSubmissionRequest, clientIP, ipLocation string) error {
	// Get email config
	config := utils.DefaultEmailConfig()

	// Recipient from configuration
	emailConfig := common.GetEmailConfig()
	to := []string{emailConfig.Recipient}

	// Subject
	subject := "New Form Submission"

	// Body
	body := fmt.Sprintf(
		"New form submission details:\n\n"+
			"Name: %s\n"+
			"Phone: %s\n"+
			"Email: %s\n"+
			"Address: %s\n"+
			"WhatsApp: %s\n"+
			"Company: %s\n"+
			"Detailed Request: %s\n"+
			"IP Address: %s\n"+
			"IP Location: %s\n",
		request.Name,
		request.Phone,
		request.Email,
		request.Address,
		request.WhatsApp,
		request.Company,
		request.DetailedRequest,
		clientIP,
		ipLocation,
	)

	log.Printf("Attempting to send email to %s", to[0])

	// Try sending using port 465 (TLS)
	err := utils.SendEmail(config, to, subject, body)
	if err != nil {
		log.Printf("Failed to send email using port 465 (TLS): %v", err)

		// Try sending using port 587 (STARTTLS)
		config = utils.SubmissionEmailConfig()
		log.Printf("Retrying with port 587 (STARTTLS)...")
		return utils.SendEmail(config, to, subject, body)
	}

	return nil
}
